﻿namespace SS.Common.ImageResizer
{
    using System;

    public class ImageSizeCalculator
    {
        private readonly double _orgWidth;
        private readonly double _orgHeight;

        public ImageSizeCalculator(double orgWidth, double orgHeight)
        {
            this._orgHeight = orgHeight;
            this._orgWidth = orgWidth;
        }

        public ImageSize Scale(int newWidth)
        {
            if (newWidth <= 0)
            {
                throw new ArgumentException(string.Format("Invalid new width: {0}", newWidth));
            }

            if (newWidth > this._orgWidth)
            {
                throw new ArgumentException("Cannot scale up, newWidth is larger than orgWidth");
            }

            var height = (int) (this._orgHeight*(newWidth/this._orgWidth));
            return new ImageSize(newWidth, height, 0, 0);
        }

        public ImageSize ScaleToFit(int newWidth, int newHeight)
        {
            if (newWidth <= 0)
            { 
                throw new ArgumentException(string.Format("Invalid new width: {0}", newWidth));
            }
            if (newHeight <= 0)
            {
                throw new ArgumentException(string.Format("Invalid new height: {0}", newHeight));
            }
            if (newWidth > this._orgWidth || newHeight > this._orgHeight)
            {
                throw new ArgumentException("Cannot scale up, new size is larger than org size");
            }

            var num1 = newWidth / this._orgWidth;
            var num2 = newHeight / this._orgHeight;
            return num2 > num1
                       ? new ImageSize(newWidth, (int) (this._orgHeight*num1), 0, 0)
                       : new ImageSize((int) (this._orgWidth*num2), newHeight, 0, 0);
        }

        public ImageSize ScaleToFill(int newWidth, int newHeight)
        {
            if (newWidth <= 0)
            {
                throw new ArgumentException(string.Format("Invalid new width: {0}", newWidth));
            }
            if (newHeight <= 0)
            {
                throw new ArgumentException(string.Format("Invalid new height: {0}", newHeight));
            }
            if (newWidth > this._orgWidth || newHeight > this._orgHeight)
            {
                throw new ArgumentException("Cannot scale up, new size is larger than org size");
            }
            var num1 = newWidth / this._orgWidth;
            var num2 = newHeight / this._orgHeight;
            return num1 > num2
                       ? new ImageSize(newWidth, newHeight, 0,
                                       (int) Math.Abs(this._orgHeight*num1 - newHeight)/2)
                       : new ImageSize(newWidth, newHeight, (int) Math.Abs(this._orgWidth*num2 - newWidth)/2, 0);
        }
    }
}
